<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        v-model="form"
        v-bind="bindVal"
        v-on="onEvent"
        :page.sync="page"
        :permission="permissionList"
        :before-open="beforeOpen"
        :before-close="beforeClose">
        <template slot="receiveTimeSearch">
            <el-date-picker
              clearable
              v-model="dates2"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
        </template>
        <template slot="searchMenu" slot-scope="{row,size}">
          <el-button :size="size" @click="()=>{searchFiledsEmpty(row);searchFiledsEmpty(searchForm)}" icon="el-icon-delete">清空</el-button>       
        </template>
        <template slot-scope="scope" slot="menuLeft">
          <el-button type="primary" size="small"
            v-permission="permissionList.submitBtn"
            @click.stop="submitBatch">发送到无效票生产申请</el-button>
          <el-button type="primary" size="small"
            v-permission="permissionList.informBtn"
            @click.stop="informBatch">通知</el-button>
          <el-button type="primary" size="small"
            v-permission="permissionList.delsBtn"
            @click.stop="delBatch">删除</el-button>
          <el-button type="primary" size="small" @click.stop="handleExport">导出</el-button>
          <el-button type="primary" size="small"
            v-permission="permissionList.inputDetailBtn" @click.stop="handleInputDetail()">入 库</el-button>
          <el-button type="primary" size="small"
            v-permission="permissionList.outDetailBtn" @click.stop="handleOutDetail()">出 库</el-button>
        </template>
        <template slot-scope="scope" slot="menu">
          <el-button
            :type="scope.type"
            :size="scope.size"
            v-permission="permissionList.editBtn"
            v-if="scope.row.checkStatus == '0'&&scope.row.outputStatus == '0'"
            @click="openEdit(scope.row,scope.index)"
          >编辑</el-button>
          <el-button
            :type="scope.type"
            :size="scope.size"
            @click.stop="openView(scope.row,scope.index)"
          >预览</el-button>
          <el-button
            :type="scope.type"
            :size="scope.size"
            v-if="(scope.row.checkStatus == '2' && scope.row.confirmStatus == '0')||(scope.row.outputStatus == '1' && scope.row.confirmStatus == '0')"
            v-permission="permissionList.completeInvalBtn"
            @click="rowCompleteInfo(scope.row,scope.index)"
          >完善信息</el-button>
        </template>
      </avue-crud>
      <open-dialog
        :DialogVisible.sync="completeInfoVisableDialog"
        title="完善信息"
        width="70%"
      >
        <el-form>
          <avue-form
            v-model="formInfo"
            :option="tableOptionStationCompleteInfo"
          ></avue-form>
          <div class="bottom-menu-invalid">
            <el-button type="primary" @click="completeInfos">保存</el-button>
            <el-button type="primary" @click="completeInfoVisableDialog = false"
              >取消</el-button
            >
          </div>
        </el-form>
      </open-dialog>
    </basic-container>
  </div>
</template>

<script>
import baseCrud from '@/mixins/base-crud'
import {dateFormat} from '@/util/date'
import { mapGetters, mapState } from 'vuex'
import {
  addObj,
  delObj,
  fetchList,
  putObj,
  exportExcel,
  submitObj,
  delsObj,
  getObj,
  completeInfo,
  informObj,inputDetailSubmit,outDetailSubmit,queryIds
} from "@/api/subway/swstinvalidticket";
import {
  tableOption,
  tableOptionAdd,
  tableOptionView,
  tableOptionStationEdit,
  tableOptionStationView,
  tableOptionStationCompleteInfo,startDate, endDate,startDate2,endDate2
} from "@/const/crud/subway/swstinvalidticket";

export default {
  name: "SwStInvalidTicket",
  mixins: [baseCrud('subway/swstinvalidticket')],
  data() {
    return {
      exportName: '无效票信息列表.xlsx',
      tableOptionAdd: tableOptionAdd,
      tableOptionView: tableOptionView,
      tableOptionStationEdit: tableOptionStationEdit,
      tableOptionStationView: tableOptionStationView,
      formInfo: [],
      completeInfoVisableDialog: false,
      tableOptionStationCompleteInfo: tableOptionStationCompleteInfo,
      searchForm: {
        dates1: [startDate, endDate],
        checkStatus: '0'
      },
      dates2: '',
      params: {
        dates2: [startDate2, endDate2]
      },
    };
  },
  computed: {
     ...mapGetters([
      'userInfo',
    ]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permissions.st_invalid_ticket_add, false),
        delBtn: this.vaildData(this.permissions.st_invalid_ticket_delete, false),
        delsBtn: this.vaildData(this.permissions.st_invalid_ticket_deletes, false),
        editBtn: this.vaildData(this.permissions.st_invalid_ticket_update, false),
        submitBtn: this.vaildData(this.permissions.st_invalid_ticket_submit, false),
        informBtn: this.vaildData(this.permissions.st_invalid_ticket_inform, false),
        completeInvalBtn: this.vaildData(this.permissions.st_invalid_ticket_completeInval, false),
        inputDetailBtn: this.vaildData(this.permissions.st_invalid_ticket_inputDetail, false),
        outDetailBtn: this.vaildData(this.permissions.st_invalid_ticket_outDetail, false)
      };
    },
  },
  watch: {
    'dates2':{
      handler(newValue, oldValue){
        if(this.validatenull(newValue)){
          this.params.dates2[0] = '';
          this.params.dates2[1] = '';
        }else{
          this.params.dates2[0] = dateFormat(newValue[0]).substr(0, 10);
          this.params.dates2[1] = dateFormat(newValue[1]).substr(0, 10);
        }
      }
    }
  },
  methods: {
    searchFiledsEmpty(form){
      this.dates2 = null;
      for (var i in form) {
        this.$delete(form,''+i+'')
      }
      this.getList(this.page);
    },
    async handleInputDetail(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
      }
      //根据id查询要入库或出库或发送无效票到生产申请的数据
      let status = await this.querys(ids);
      if(status == true){
        this.$confirm("确认加入入库?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          inputDetailSubmit(ids)
            .then(data => {
              this.$message.success("入库成功");
              this.getList(this.page);
              done();
            })
            .catch(() => {});
        });
      }else{
        return false;
      }
    },
    //根据id查询要入库或出库或发送无效票到生产申请的数据
    async querys(ids){
      let status = false; 
      await queryIds({ids:ids}).then((res) => {
        if(res.data.code == 0){
          status =  true;
        }
      }).catch(() => {});
        return status;
    },
    async handleOutDetail(){
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请选择数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
      }
      //根据id查询要入库或出库或发送无效票到生产申请的数据
      let status = await this.querys(ids);
      if(status == true){
        this.$confirm("请确认是否加入出库，出库后不能撤回?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          outDetailSubmit(ids)
            .then(data => {
              this.$message.success("出库成功");
              this.getList(this.page);
              done();
            })
            .catch(() => {});
        });
      }else{
        return false;
      }
    },
    informBatch: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请勾选数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
        if(table.checkStatus !=2&&table.outputStatus !='1'){
          this.$message.error("只有审核通过或已出库的数据才能通知!");
          return false;
        }
        if(table.confirmStatus !=0){
          this.$message.error("请检查要通知的数据!");
          return false;
        }
      }
      informObj(ids)
        .then((data) => {
          this.$message.success("通知成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    rowCompleteInfo: function (row) {
      row.$cellEdit = true;
      getObj(row.id)
        .then((response) => {
          let res = response.data.data;
          this.formInfo = res;
        })
        .then(() => {
          this.completeInfoVisableDialog = true;
        });
    },
    completeInfos: function () {
      if (this.formInfo.newCardOrder.length != 10) {
        this.$message.info("新卡号必须输入10位!");
        return;
      }
      completeInfo(this.formInfo)
        .then((data) => {
          this.$message.success("完善信息成功");
          this.completeInfoVisableDialog = false;
          this.getList(this.page);
          done();
        })
        .catch(() => {});
    },
    async submitBatch() {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请勾选数据");
        return false;
      }
      let id = [];
      let ids = this.$refs.crud.tableSelect;
      for(const table of ids){
        if(table.checkStatus !=0){
          this.$message.error("不能重复提交数据!");
          return false;
        }
        if(table.outputStatus =='1'){
          this.$message.error("已出库的数据不允许提交!");
          return false;
        }
        id.push(table.id)
      }
      //根据id查询要入库或出库或发送无效票到生产申请的数据
      let status = await this.querys(id);
      if(status == true){
        submitObj(ids)
          .then((data) => {
            this.$message.success("提交成功");
            this.getList(this.page);
            done();
          })
          .catch(() => {
            loading();
          });
      }else{
        return false;
      }
    },
    delBatch: function () {
      if (this.$refs.crud.tableSelect.length < 1) {
        this.$message.error("请勾选数据");
        return false;
      }
      let ids = [];
      for (const table of this.$refs.crud.tableSelect) {
        ids.push(table.id);
        if(table.checkStatus !=0){
          this.$message.error("已提交的数据不能删除!");
          return false;
        }
        if(table.checkStatus !=0){
          this.$message.error("已通知的数据不能删除!");
          return false;
        }
      }
      delsObj(ids)
        .then((data) => {
          this.$message.success("删除成功");
          this.getList(this.page);
          done();
        })
        .catch(() => {
          loading();
        });
    },
    openView(row, index) {
      if (row.dataSource === "0") {
        this.tableOption = tableOptionStationView;
      }
      if (row.dataSource === "1") {
        this.tableOption = tableOptionView;
      }
      this.$refs.crud.rowView(row, index);
      return;
    },
    openEdit(row, index) {
      if (row.dataSource === "0") {
        this.tableOption = tableOptionStationEdit;
      }
      if (row.dataSource === "1") {
        this.tableOption = tableOption;
      }
      this.$refs.crud.rowEdit(row, index);
    },
    beforeOpen(done, type) {
      if (["view", "edit"].includes(type)) {
        // 查看和编辑逻辑
        //console.log("预览进来了");
      } else {
        setTimeout(() => {
          this.tableOption = tableOptionAdd;
          this.form.applyTime=dateFormat(new Date()).slice(0,10);
          this.form.cardIssuer=this.userInfo.nikename;
          this.form.cardIssuerId=this.userInfo.userCode;
        }, 0);
      }
      done();
    },
    beforeClose(done, type) {
      this.tableOption = tableOption;
      done();
    }
  }
}
</script>

<style lang="scss" scoped>
.bottom-menu-invalid {
  text-align: center;
}
</style>
